import { CURRENCIES } from '@/constants/global'
import { GET_INIT_INFO, SET_CURRENCY, SET_LANG, SET_SWIPER } from '@/constants/mutation-types'
import { currencyStorage, homeSwiperStorage, initInfoStorage, langStorage } from '@/utils/storage'
import { IMG_BASE_URL } from '@/config'
import * as API from '@/constants/api'

const isProd = process.env.CONTEXT === 'production'
const isTest = Boolean(process.env.DEPLOY_PRIME_URL && !isProd)
const initInfo = {
  download_img_url: '',
  site: {
    app_name: '',
    logo_app: ''
  },
  via_websocket_url: ''
}

let currency = currencyStorage.get()
if (!currency) {
  currency = CURRENCIES[Object.keys(CURRENCIES)[0]]
  currencyStorage.set(currency)
}

export const state = () => ({
  host:
    (isProd ? process.env.URL : process.env.DEPLOY_PRIME_URL) ||
    'http://0.0.0.0:3000',
  isProd,
  isTest,
  isDev: !isProd && !isTest,
  locale: langStorage.get(),
  homeSwiper: homeSwiperStorage.get() || [],
  currency, // 货币设置
  platform: 'android', // android/ios/web
  initInfo: initInfoStorage.get() || initInfo,
  imgBaseUrl: IMG_BASE_URL
})

export const mutations = {
  [SET_LANG] (state, locale) {
    state.locale = locale
  },
  [GET_INIT_INFO] (state, payload) {
    state.initInfo = payload
  },
  [SET_CURRENCY] (state, value) {
    state.currency = value
  },
  [SET_SWIPER] (state, data) {
    state.homeSwiper = data
  }
}

export const actions = {
  setLang ({ commit }, locale) {
    langStorage.set(locale)
    commit(SET_LANG, locale)
  },
  setCurrency ({ commit }, data) {
    currencyStorage.set(data)
    commit(SET_CURRENCY, data)
  },
  async getInitInfo ({ commit }) {
    const { data } = await this.$axios.$post(API.GET_INIT_INFO)
    data.usd_to_cny = 1
    commit(`market/${GET_INIT_INFO}`, data.usd_to_cny)
    initInfoStorage.set(data)
    commit(GET_INIT_INFO, data)
  },
  async getSlides ({ commit }, params) {
    const { data } = await this.$axios.$post(API.GET_SLIDES, params)
    homeSwiperStorage.set(data)
    commit(SET_SWIPER, data)
  },
  async getRecommend ({ commit }, params) {
    return await this.$axios.$post(API.GET_RECOMMEND, params)
  }
}
